package com.nageoffer.shortlink.admin.config;

import com.nageoffer.shortlink.admin.common.biz.user.UserFlowRiskControlFilter;
import com.nageoffer.shortlink.admin.common.biz.user.UserTransmitFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 用户配置自动装配
 */
@Configuration
public class UserConfiguration {

    /**
     * 用户信息传递过滤器
     */
    @Bean
    public FilterRegistrationBean<UserTransmitFilter> globalUserTransmitFilter() {
        FilterRegistrationBean<UserTransmitFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new UserTransmitFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(0);
        return registration;
    }

    /**
     * 用户操作流量风控过滤器
     */
    @Bean
// 条件装配：仅当配置项short-link.flow-limit.enable=true时生效[1,3](@ref)
    @ConditionalOnProperty(name = "short-link.flow-limit.enable", havingValue = "true")
    public FilterRegistrationBean<UserFlowRiskControlFilter> globalUserFlowRiskControlFilter(
            // 注入Redis操作模板，用于执行Lua限流脚本[4](@ref)
            StringRedisTemplate stringRedisTemplate,
            // 注入流量风控配置（时间窗口、最大访问次数等）[1](@ref)
            UserFlowRiskControlConfiguration userFlowRiskControlConfiguration) {
        // 创建过滤器注册Bean实例
        FilterRegistrationBean<UserFlowRiskControlFilter> registration = new FilterRegistrationBean<>();
        // 设置自定义过滤器实例，传入Redis客户端和配置参数[1,4](@ref)
        registration.setFilter(new UserFlowRiskControlFilter(stringRedisTemplate, userFlowRiskControlConfiguration));
        // 配置拦截所有请求路径（/*）[6](@ref)
        registration.addUrlPatterns("/*");
        // 设置过滤器执行顺序（数值越小优先级越高，此处设为10）[6](@ref)
        registration.setOrder(10);
        return registration;
    }
}